#include "UtilSystem.h"

std::tuple<int, QString> UtilSystem::execCmd(const QString &cmd)
{
    QString Result;
    QProcess exec;
    exec.setProgram("/bin/bash");
    exec.setArguments({"-c",cmd});
    exec.start();
    exec.waitForFinished();
    if(exec.exitCode() < 0)
    {
        Result = exec.readAllStandardError();
        return std::make_tuple(-1,Result);
    }
    Result = exec.readAllStandardOutput();
    return std::make_tuple(0,Result);
}

qint64 UtilSystem::getPid()
{
    return QCoreApplication::applicationPid();
}

void UtilSystem::singleProcess(char **argv)
{
    QString name = strrchr(argv[0],'/')+1;
    QString cmd = QString("pgrep -a %1 | wc -l").arg(name);
    int Err;QString Res;
    std::tie(Err,Res) = execCmd(cmd);
    if( Res.toInt() > 1)
    {
        std::tie(Err,Res) = execCmd(QString("pgrep -a %1").arg(name));
        qInfo().noquote() << "current pid:" << getPid();
        qCritical().noquote() << Res;
        std::exit(0);
    }
    qout.noquote() << Res;
}
